package cate.game.server.configuration.dao.role;

import cate.game.db.mongo.RoleBaseDao;
import cate.game.role.base.RoleBase;
import cate.game.server.configuration.dao.MgRolePartDao;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import easy.java.practice.errorcode.EcException;
import easy.mongo.template.MgWhere;
import org.bson.Document;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

public class MgRoleBaseDao extends MgRolePartDao<RoleBase> implements RoleBaseDao {

    @Override
    protected Class<RoleBase> getEntityClass() {
        return RoleBase.class;
    }

    @Override
    public Page<RoleBase> findByName(String name, Pageable page) {
        throw new EcException("尚未实现");
    }

    @Override
    public List<RoleBase> searchByName(String name, int limitNum) {
        try {
            List<RoleBase> result = new ArrayList<>();
            MgWhere where = new MgWhere().like("name", name);
            FindIterable<Document> fi = collection.find(where.toAndFilter()).limit(limitNum);
            MongoCursor<Document> iterator = fi.iterator();
            while(iterator.hasNext()) {
                Document doc = iterator.next();
                result.add( getMapper().decode(doc, getEntityClass()) );
            }
            return result;
        } catch (Exception e) {
            throw new EcException(e);
        }
    }
}
